<template>
  <view class="page">
    <!-- 轮播图 -->
    <view class="section banner-section" v-if="banners.length">
      <swiper class="banner-swiper" :autoplay="true" :interval="3000" :circular="true">
        <swiper-item v-for="item in banners" :key="item._id" class="banner-item" @click="handleBannerTap(item)">
          <image class="banner-image" :src="getImageSrc(item.image)" mode="aspectFill" />
          <!-- 移除标题显示 -->
        </swiper-item>
      </swiper>
    </view>

    

    <!-- 分类入口 -->
    <view class="section category-section">
      <view class="section-title">分类</view>
      <view v-if="categories.length" class="category-grid">
        <view class="category-item" v-for="item in categories" :key="item._id" @click="handleCategoryTap(item)">
          <image v-if="getCategoryIcon(item)" class="category-icon" :src="getCategoryIcon(item)" mode="aspectFill" />
          <view v-else class="category-icon">
            <uni-icons type="image" color="#9CA3AF" :size="36" />
          </view>
          <view class="category-name">{{ item.name }}</view>
        </view>
      </view>
      <view v-else class="category-empty">暂无分类</view>
    </view>

    <!-- 推荐菜品 -->
    <view class="section dish-section" v-if="recommendedDishes.length">
      <view class="section-title">推荐菜品</view>
      <view class="dish-waterfall">
        <view class="wf-col">
          <view v-for="item in leftColumn" :key="item._id" class="dish-card-wrapper" @click="handleDishTap(item)">
            <UniCard :isShadow="true" :border="false" :isFull="true">
              <view class="dish-image-wrapper">
                <image class="dish-image" :src="getImageSrc(item.image)" mode="aspectFill" />
                <view class="cart-btn" @click.stop="addToCart(item)">
                  <uni-icons type="cart" color="#ef4444" :size="22" />
                </view>
                <view class="favorite-btn" @click.stop="toggleFavorite(item)">
                  <uni-icons 
                    :type="isFavorited(item._id) ? 'heart-filled' : 'heart'" 
                    :color="isFavorited(item._id) ? '#ef4444' : '#ffffff'" 
                    :size="22" 
                  />
                </view>
              </view>
              <view class="dish-info">
                <view class="dish-header">
                  <view class="dish-name">{{ item.name }}</view>
                  <view class="spice-badge" :class="getSpicinessClass(item.spiciness)">{{ getSpicinessText(item.spiciness) }}</view>
                </view>
                <view class="dish-desc" v-if="item.description">{{ item.description }}</view>
              </view>
            </UniCard>
          </view>
        </view>
        <view class="wf-col">
          <view v-for="item in rightColumn" :key="item._id" class="dish-card-wrapper" @click="handleDishTap(item)">
            <UniCard :isShadow="true" :border="false" :isFull="true">
              <view class="dish-image-wrapper">
                <image class="dish-image" :src="getImageSrc(item.image)" mode="aspectFill" />
                <view class="cart-btn" @click.stop="addToCart(item)">
                  <uni-icons type="cart" color="#ef4444" :size="22" />
                </view>
                <view class="favorite-btn" @click.stop="toggleFavorite(item)">
                  <uni-icons 
                    :type="isFavorited(item._id) ? 'heart-filled' : 'heart'" 
                    :color="isFavorited(item._id) ? '#ef4444' : '#ffffff'" 
                    :size="22" 
                  />
                </view>
              </view>
              <view class="dish-info">
                <view class="dish-header">
                  <view class="dish-name">{{ item.name }}</view>
                  <view class="spice-badge" :class="getSpicinessClass(item.spiciness)">{{ getSpicinessText(item.spiciness) }}</view>
                </view>
                <view class="dish-desc" v-if="item.description">{{ item.description }}</view>
              </view>
            </UniCard>
          </view>
        </view>
      </view>
      <uni-load-more :status="loadMoreStatus" />
    </view>

    <!-- 空态占位 -->
    <view class="empty" v-if="!loading && !banners.length && !categories.length && !recommendedDishes.length">
      <text>暂无内容</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app'
import UniCard from '../../uni_modules/uni-card/components/uni-card/uni-card.vue'
import cart from '@/common/cart.js'
import { getImageSrc } from '@/common/image.js'
import { getSpicinessText, getSpicinessClass } from '@/common/dish.js'
import { addFavorite, removeFavorite, batchCheckFavorites } from '@/common/favorite.js'

const banners = ref([])
const categories = ref([])
const recommendedDishes = ref([])
const loading = ref(false)
const recommendedPage = ref(1)
const recommendedPageSize = ref(5)
const loadMoreStatus = ref('more')
const totalRecommendedPages = ref(1)
const isLoadingMore = ref(false)
const favoriteMap = ref({})
 

const leftColumn = computed(() => recommendedDishes.value.filter((_, idx) => idx % 2 === 0))
const rightColumn = computed(() => recommendedDishes.value.filter((_, idx) => idx % 2 === 1))

async function loadBanners() {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-banners',
      data: { action: 'get-banners', data: { page: 1, pageSize: 10, status: '1', sortField: 'sort', sortOrder: 'desc' } }
    })
    if (res.result && res.result.code === 200) {
      banners.value = (res.result.data && res.result.data.list) || []
    }
  } catch (err) {
  }
}

async function loadCategories() {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-categories',
      data: { action: 'get-categories', data: { page: 1, pageSize: 100, status: '', sortField: 'sort', sortOrder: 'asc' } }
    })
    if (res.result && res.result.code === 200) {
      const list = (res.result.data && res.result.data.list) || []
      categories.value = list.filter(item => Number(item.status) === 1)
    } else {
    }
  } catch (err) {
  }
}

async function loadRecommendedDishes(append = false) {
  try {
    const page = append ? recommendedPage.value + 1 : 1
    const res = await uniCloud.callFunction({
      name: 'food-dishes',
      data: { action: 'get-dishes', data: { page, pageSize: recommendedPageSize.value, isRecommended: 'true', sortField: 'create_date', sortOrder: 'desc' } }
    })
    if (res.result && res.result.code === 200) {
      const list = (res.result.data && res.result.data.list) || []
      totalRecommendedPages.value = res.result.data.totalPages || 1
      recommendedPage.value = page
      recommendedDishes.value = append ? recommendedDishes.value.concat(list) : list
      loadMoreStatus.value = recommendedPage.value >= totalRecommendedPages.value ? 'noMore' : 'more'
      
      // 批量检查收藏状态
      await loadFavoritesStatus()
    }
  } catch (err) {
  }
}

// 加载收藏状态
async function loadFavoritesStatus() {
  if (recommendedDishes.value.length === 0) return
  const dishIds = recommendedDishes.value.map(item => item._id)
  favoriteMap.value = await batchCheckFavorites(dishIds)
}

// 切换收藏状态
async function toggleFavorite(dish) {
  const dishId = dish._id
  const currentFav = favoriteMap.value[dishId]
  
  if (currentFav && currentFav.isFavorite) {
    // 取消收藏
    const result = await removeFavorite(currentFav.favorite_id)
    if (result.success) {
      uni.showToast({ title: result.message, icon: 'success' })
      favoriteMap.value[dishId] = { isFavorite: false, favorite_id: null }
    }
    // 失败时不显示提示（工具函数已处理登录引导）
  } else {
    // 添加收藏
    const result = await addFavorite(dish)
    if (result.success) {
      uni.showToast({ title: result.message, icon: 'success' })
      favoriteMap.value[dishId] = { isFavorite: true, favorite_id: result.favorite_id }
    }
    // 失败时不显示提示（工具函数已处理登录引导）
  }
}

// 检查是否已收藏
function isFavorited(dishId) {
  return favoriteMap.value[dishId]?.isFavorite || false
}

function getSpicinessCount(level) {
  const n = Number(level) || 0
  if (n <= 0) return 0
  return Math.min(n, 4)
}

function getSpicinessColor(level) {
  const n = Math.max(1, Math.min(Number(level) || 0, 4))
  const map = {
    1: '#fca5a5', // 微辣 浅红
    2: '#f87171', // 中辣 中红
    3: '#ef4444', // 重辣 深红
    4: '#b91c1c'  // 特辣 更深红
  }
  return map[n] || '#ef4444'
}
function getCategoryIcon(item) {
  const src = item?.image ?? item?.icon ?? null
  return getImageSrc(src)
}

function handleBannerTap(item) {
  const type = Number(item?.link_type ?? 0)
  const link = (item?.link_value || '').trim()

  if (type === 1 && /^https?:\/\//.test(link)) {
    // #ifdef H5
    window.open(link, '_blank')
    // #endif
    // #ifndef H5
    uni.showToast({ title: '外部链接暂未适配此平台', icon: 'none' })
    // #endif
    return
  }
  if (type === 2 && link) {
    const url = link.startsWith('/') ? link : `/${link}`
    uni.navigateTo({ url })
    return
  }
  uni.showToast({ title: item.title || '轮播图', icon: 'none' })
}

function handleCategoryTap(item) {
  uni.switchTab({
    url: '/pages/category/category'
  })
  // 将分类 ID 保存到本地存储，分类页在加载时读取
  uni.setStorageSync('targetCategoryId', item._id)
}

function handleDishTap(item) {
  uni.navigateTo({
    url: `/pages/dish-detail/dish-detail?id=${item._id}`
  })
}

function addToCart(item) {
  cart.addItem(item, 1)
  uni.showToast({ title: '已加入已点', icon: 'success' })
  cart.syncTabBadge(2)
}
 

onReachBottom(async () => {
  if (isLoadingMore.value) return
  if (recommendedPage.value < totalRecommendedPages.value) {
    loadMoreStatus.value = 'loading'
    isLoadingMore.value = true
    await loadRecommendedDishes(true)
    isLoadingMore.value = false
    loadMoreStatus.value = recommendedPage.value >= totalRecommendedPages.value ? 'noMore' : 'more'
  }
})

onLoad(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadBanners(),
      loadCategories(),
      loadRecommendedDishes()
    ])
  } catch (e) {
    uni.showToast({ title: '加载失败，请稍后重试', icon: 'none' })
  } finally {
    loading.value = false
  }
})

onShow(() => {
  cart.syncTabBadge(2)
})
</script>

<style lang="scss" scoped>
$spacing: 20rpx;
$radius: 12rpx;
$badge-radius: 100rpx;
$shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
$text-muted: #8f8f94;

$banner-height: 300rpx;
$dish-image-height: 200rpx;

$mild-bg: #f1f5f9; $mild-color: #334155;
$light-bg: #fde68a; $light-color: #92400e;
$medium-bg: #fca5a5; $medium-color: #7f1d1d;
$hot-bg: #ef4444; $hot-color: #fff;

/* 现代化配色与阴影 */
$bg: #f8fafc;
$card-bg: #ffffff;
$border-color: #eaeaf0;
$brand: #6C5CE7;
$shadow-soft: 0 8rpx 20rpx rgba(0, 0, 0, 0.06);
$radius-lg: 16rpx;

@mixin spiciness-badge($bg, $color) {
  background: $bg;
  color: $color;
}

.page {
  display: flex;
  flex-direction: column;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);

  .section { padding: $spacing; }

  .section-title {
    font-size: 36rpx;
    font-weight: 800;
    margin-bottom: 20rpx;
    color: #0f172a;
    letter-spacing: -0.5rpx;
    border-left: 8rpx solid $brand;
    padding-left: 20rpx;
    line-height: 1.2;
  }

  /* 轮播 */
  .banner-swiper {
    height: $banner-height;
    border-radius: $radius-lg;
    overflow: hidden;
    box-shadow: $shadow-soft;
  }

  .banner-item {
    position: relative;

    .banner-image {
      width: 100%;
      height: 100%;
    }

    .banner-title {
      position: absolute;
      left: $spacing;
      bottom: $spacing;
      padding: 12rpx 16rpx;
      background: rgba(0, 0, 0, 0.6);
      color: #fff;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: 600;
      line-height: 1.2;
    }
  }

  /* 分类 */
  .category-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
  }

  .category-item {
    width: calc((100% - 16rpx * 2) / 3);
    box-sizing: border-box;
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    border: none;
    padding: 16rpx 8rpx;
    text-align: center;
    transition: transform 0.2s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .category-item:nth-child(3n) { margin-right: 0; } /* 改为3n选择器 */
  .category-item:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .category-item:nth-child(4n) { margin-right: 0; }

  .category-empty {
    padding: 32rpx;
    color: $text-muted;
    font-size: 28rpx;
    text-align: center;
    line-height: 1.4;
  }

  .category-icon { 
    width: 80rpx; 
    height: 80rpx; 
    border-radius: 0; 
    object-fit: contain; 
    margin-bottom: 16rpx; 
    background: transparent; 
    display: inline-flex; 
    align-items: center; 
    justify-content: center; 
  }
  .category-name { 
    font-size: 30rpx; 
    font-weight: 700; 
    color: #1f2937;
    line-height: 1.3;
  }
  .category-item:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .category-item:nth-child(4n) { margin-right: 0; }

  .category-empty {
    padding: 32rpx;
    color: $text-muted;
    font-size: 28rpx;
    text-align: center;
    line-height: 1.4;
  }

  /* 推荐菜品 - 瀑布流两列 */
  .dish-waterfall { display: flex; gap: 20rpx; align-items: stretch; }
  .wf-col { width: calc((100% - 20rpx) / 2); display: flex; flex-direction: column; gap: 20rpx; }
  .dish-card-wrapper { width: 100%; display: flex; }
  .dish-image { width: 100%; height: $dish-image-height; border-radius: $radius-lg; transition: transform .2s ease; }
  .dish-card-wrapper:active .dish-image { transform: scale(.98); }

  /* 菜品图片容器与购物车按钮（右上角覆盖） */
  .dish-image-wrapper { position: relative; }
  .cart-btn {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 48rpx;
    height: 48rpx;
    background: #ffffff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }
  .cart-btn:active { transform: scale(0.96); }

  /* 收藏按钮（左上角） */
  .favorite-btn {
    position: absolute;
    top: 10rpx;
    left: 10rpx;
    width: 48rpx;
    height: 48rpx;
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(8rpx);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    transition: all 0.2s ease;
  }
  .favorite-btn:active { 
    transform: scale(0.9); 
  }

  .dish-info {
    padding: 20rpx;

    .dish-header {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 8rpx;
      .header-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 8rpx; }
    }

    .dish-name {
      font-size: 32rpx;
      font-weight: 700;
      color: #0f172a;
      line-height: 1.3;
      flex: 1;
    }

    .spice-badge {
      margin-top: 0;
      display: inline-flex;
      align-items: center;
      padding: 8rpx 16rpx;
      border-radius: $badge-radius;
      font-size: 24rpx;
      font-weight: 600;
      line-height: 1;
      white-space: nowrap;
    }
    .spice-badge.mild { @include spiciness-badge($mild-bg, $mild-color); }
    .spice-badge.light { @include spiciness-badge($light-bg, $light-color); }
    .spice-badge.medium { @include spiciness-badge($medium-bg, $medium-color); }
    .spice-badge.hot { @include spiciness-badge($hot-bg, $hot-color); }

    .dish-desc {
      margin-top: 12rpx;
      font-size: 28rpx;
      color: #64748b;
      line-height: 1.4;
    }
  }

  /* 空态 */
  .empty { 
    padding: 80rpx; 
    text-align: center; 
    color: $text-muted; 
    font-size: 30rpx;
    line-height: 1.4;
  }
}
</style>
